﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using System.Xml.Linq;

namespace Utils
{
    public static class FileManager
    {
        public static XDocument ReadXDocument(string path)
        {
            if (String.IsNullOrWhiteSpace(path))
                return null;

            XDocument xDoc = new XDocument();
            try
            {
                xDoc = XDocument.Load(path);
            }
            catch
            {
                return null;
            }
            return xDoc;
        }

        public static void WriteLineToTxtFile(string path, string text)
        {
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }

            using (FileStream fStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, 4*1024*1024, true))
            {
                fStream.Position = fStream.Length;

                using (StreamWriter sWriter = new StreamWriter(fStream, Encoding.Unicode))
                {
                    sWriter.WriteLine(text);
                }
            }
        }

        public static void DownloadFileToServerFolder(Uri uri, string filePath, HttpServerUtilityBase server)
        {
            using (WebClient webClient = new WebClient())
            {               
                webClient.DownloadFile(uri, server.MapPath(filePath));
            }
        }
    }
}
